/**
 * @作者:黎谢之
 * @创建时间：2021/7/7
 * @修改时间：2021/7/14
 */
package com.example.senior_bug.Service;

import com.example.senior_bug.EntityClass.*;
import com.example.senior_bug.Repository.*;
import com.example.senior_bug.ToolClass.Options;
import com.example.senior_bug.ToolClass.Result;
import com.example.senior_bug.enm.MsgId;
import com.example.senior_bug.utils.OptionsUtils;
import com.example.senior_bug.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SKUService {
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private BrandRepository brandRepository;
    @Autowired
    private GoodRepository goodRepository;
    @Autowired
    private SKURepository skuRepository;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private CustomerRepository customerRepository;

    /*发布商品页面获取所有品牌相关信息
     *
     * */
    public Result GetAllOption() {
        List<Channel> channels = (List<Channel>) channelRepository.findAll();
        List<Options> select = new ArrayList<>();
        for (Channel channel :
                channels) {
            Options channelOption = new Options();
            channelOption.setLabel(channel.getName());
            channelOption.setValue(channel.getName());
            List<Options> categorySelect = new ArrayList<>();
            for (Category category :
                    channel.getCategories()) {
                Options categoryOption = new Options();
                categoryOption.setLabel(category.getName());
                categoryOption.setValue(category.getName());
                List<Options> brandSelect = new ArrayList<>();
                for (Brand brand :
                        category.getBrands()) {
                    Options brandOption = new Options();
                    brandOption.setLabel(brand.getName());
                    brandOption.setValue(brand.getName());
                    List<Options> goodSelect = new ArrayList<>();
                    for (Good good :
                            brand.getGoods()) {
                        Options goodOption = new Options();
                        goodOption.setLabel(good.getName());
                        goodOption.setValue(good.getName());
                        goodSelect.add(goodOption);
                    }
                    brandOption.setChildren(goodSelect);
                    brandSelect.add(brandOption);
                }
                categoryOption.setChildren(brandSelect);
                categorySelect.add(categoryOption);
            }
            channelOption.setChildren(categorySelect);
            select.add(channelOption);
        }
        OptionsUtils.setSelect(select);
        return ResultUtils.success(OptionsUtils.getSelect());
    }

    /*测试函数
     * */
    public Result FindAllSku() {
        return ResultUtils.success(skuRepository.findAll());
    }

    /*用户二级页面通过传入：
     * 1.二级分类名字(CategoryName)
     * 2.三级分类名字(BrandName)
     * 3.单页需要SKU数量(Take)
     * 4.页码数(Page)
     * 获取SKU列表
     * 7.13检查无问题
     * */
    public Result GetSkuByCategoryAndBrandAndTakeAndPage(String CategoryName, String BrandName, int Take, int Page, String type) {
        if (categoryRepository.existsByName(CategoryName) && (BrandName.equals("全部") || brandRepository.existsByName(BrandName))) {
            List<SKU> query = new ArrayList<>();
            if (BrandName.equals("全部")) {
                Category category = categoryRepository.findByName(CategoryName);
                for (SKU item :
                        skuRepository.findAll()) {
                    if (item.getState().equals("已上架") && brandRepository.findById(goodRepository.findById(item.getGoodId()).getBrandId()).getCategoryId() == category.getId())
                        query.add(item);
                }

            } else {
                Brand brand = brandRepository.findByNameAndCategoryId(BrandName, categoryRepository.findByName(CategoryName).getId());
                for (SKU item :
                        skuRepository.findAll()) {
                    if (item.getState().equals("已上架") && goodRepository.findById(item.getGoodId()).getBrandId() == brand.getId())
                        query.add(item);
                }
            }

            switch (type) {
                case "销量升序":
                    query.sort((SKU sku1, SKU sku2) -> sku1.getSales() - sku2.getSales());
                    break;
                case "销量降序":
                    query.sort((SKU sku1, SKU sku2) -> sku2.getSales() - sku1.getSales());
                    break;
                case "价格升序":
                    query.sort((SKU sku1, SKU sku2) -> (int) (sku1.getSkuSpecificationOptions().get(0).getPrice()
                            - sku2.getSkuSpecificationOptions().get(0).getPrice()));
                    break;
                case "价格降序":
                    query.sort((SKU sku1, SKU sku2) -> (int) (sku2.getSkuSpecificationOptions().get(0).getPrice()
                            - sku1.getSkuSpecificationOptions().get(0).getPrice()));
                    break;
                default:
                    break;
            }

            return (query.size() < Take) ? ResultUtils.success(query)
                    : ResultUtils.success(query.subList((Page - 1) * Take, Page * Take));
        } else {
            return ResultUtils.error(MsgId.ANYSKU_NOT_FOUND);
        }
    }

    /*用户二级界面分页获取SKU总数
     * 1.二级分类名(CategoryName)
     * 2.品牌名(BrandName)
     * 7.14
     * */
    public Result GetSumOfSkuByCategoryNameAndBrandName(String CategoryName, String BrandName) {
        if (categoryRepository.existsByName(CategoryName) && (BrandName.equals("全部") || brandRepository.existsByName(BrandName))) {
            int Sum = 0;
            if (BrandName.equals("全部")) {
                Category category = categoryRepository.findByName(CategoryName);
                for (SKU item :
                        skuRepository.findAll()) {
                    if (item.getState().equals("已上架") && brandRepository.findById(goodRepository.findById(item.getGoodId()).getBrandId()).getCategoryId() == category.getId())
                        Sum++;
                }

            } else {
                Brand brand = brandRepository.findByNameAndCategoryId(BrandName, categoryRepository.findByName(CategoryName).getId());
                for (SKU item :
                        skuRepository.findAll()) {
                    if (item.getState().equals("已上架") && goodRepository.findById(item.getGoodId()).getBrandId() == brand.getId())
                        Sum++;
                }
            }
            return ResultUtils.success(Sum);
        } else {
            return ResultUtils.error(MsgId.ANYSKU_NOT_FOUND);
        }
    }

    /*通过传入Sku的ID获取对应Sku(用户查看商品详情页)
     * 1.SKU主键(Id)
     * 获取SKU对象
     * 7.13检查无问题
     * */
    public Result GetSkuById(int Id) {
        if (skuRepository.existsById(Id)) {
            SKU sku = skuRepository.findById(Id);
            if (sku.getComments().size() > 0) {
                for (Comment item :
                        sku.getComments()) {
                    Customer customer = customerRepository.findById(item.getCustomerId());
                    item.setCustomerName(customer.getName());
                    item.setFaceImageUrl(customer.getFaceUrl());
                }
            }
            sku.setBusinessuuid(businessRepository.findById(sku.getBusinessId()).getUuid());
            return ResultUtils.success(sku);
        } else {
            return ResultUtils.error(MsgId.SKU_NOT_FOUND);
        }
    }

    /*用户二级页面通过传入：
     * 1.二级分类名字(CategoryName)
     * 2.单页需要SKU数量(Take)
     * 3.页码数(Page)
     * 获取对应二级分类的所有品牌的SKU列表
     * 7.13修改bug：应该get上一级ID而不是本级ID
     * */
    public Result GetSkuByCategory(String CategoryName, int Take, int Page, String Type) {
        if (categoryRepository.existsByName(CategoryName)) {
            List<SKU> skus = new ArrayList<>();
            for (SKU item :
                    skuRepository.findAll()) {
                if (item.getState().equals("已上架") && categoryRepository.findById(brandRepository.findById(goodRepository.findById(item.getGoodId()).getBrandId()).getCategoryId()).getName().equals(CategoryName)) {
                    skus.add(item);
                }
            }

            switch (Type) {
                case "销量升序":
                    skus.sort((SKU sku1, SKU sku2) -> sku1.getSales() - sku2.getSales());
                    break;
                case "销量降序":
                    skus.sort((SKU sku1, SKU sku2) -> sku2.getSales() - sku1.getSales());
                    break;
                case "价格升序":
                    skus.sort((SKU sku1, SKU sku2) -> (int) (sku1.getSkuSpecificationOptions().get(0).getPrice()
                            - sku2.getSkuSpecificationOptions().get(0).getPrice()));
                    break;
                case "价格降序":
                    skus.sort((SKU sku1, SKU sku2) -> (int) (sku2.getSkuSpecificationOptions().get(0).getPrice()
                            - sku1.getSkuSpecificationOptions().get(0).getPrice()));
                    break;
                default:
                    break;
            }

            return ResultUtils.success((skus.size() > Take) ? skus.subList((Page - 1) * Take, Page * Take) : skus);
        } else {
            return ResultUtils.error(MsgId.CATEGORY_NOT_FOUND);
        }
    }

    /*用户界面的搜索栏
     * 1.KeyWords用户输入的关键词
     * 7.13添加新判断：对厂商店铺名字也搜索KeyWords
     * */
    public Result FindSkuByKeyWords(String KeyWords) {
        List<SKU> query = new ArrayList<>();

        for (SKU item :
                skuRepository.findAll()) {
            if (item.getState().equals("已上架") &&
                    (item.getName().contains(KeyWords) ||
                            goodRepository.findById(item.getGoodId()).getName().contains(KeyWords) ||
                            businessRepository.findById(item.getBusinessId()).getStoreName().contains(KeyWords) ||
                            brandRepository.findById(goodRepository.findById(item.getGoodId()).getBrandId()).getName().contains(KeyWords) ||
                            categoryRepository.findById(brandRepository.findById(goodRepository.findById(item.getGoodId()).getBrandId()).getCategoryId()).getName().contains(KeyWords) ||
                            channelRepository.findById(categoryRepository.findById(brandRepository.findById(goodRepository.findById(item.getGoodId()).getBrandId()).getCategoryId()).getChannelId()).getName().contains(KeyWords))
            ) {
                query.add(item);
            }
        }

        if (query.size() > 0) {
            return ResultUtils.success(query);
        } else {
            return ResultUtils.error(MsgId.KEYWORDS_NOT_FOUND);
        }
    }

    /*首页销量前面的商品
     *
     * */
    public Result getSortBySales() {
        List<SKU> skus = skuRepository.findAll();
        skus.sort((SKU sku1, SKU sku2) -> sku2.getSales() - sku1.getSales());
        return ResultUtils.success(skus);
    }

}
